package view;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

import model.Contact;

/**
 * This class defines a window to edit or create a contact and save it
 * @author alexisstefanski
 *
 */
public class ContactFrame extends JFrame implements ActionListener {

	/**
	 * Automatically generated by eclipse with implementation of ActionListener
	 */
	private static final long serialVersionUID = 1L;
	
	/* GUI Elements */
	private JPanel mainPanel;
	private JPanel leftPanel;
	private JPanel rightPanel;
	private JPanel boxPanel;
	private JFileChooser imgChooser;
	private JButton choseButton;
	private JButton addButton;
	private JButton saveButton;
	private JLabel imgName;
	private Contact contact;
	
	/* Keep a reference of the main Frame of the application */
	private MainFrame mainFrame;
	
	private static final int FIRST_NAME = 0;
	private static final int LAST_NAME = 1;
	private static final int HOME_PHONE = 2;
	private static final int HOME_ADDRESS = 3;
	private static final int WORK_PHONE = 4;
	private static final int WORK_ADDRESS = 5;
	private static final int MOBILE = 6;
	private static final int WORK_MOBILE = 7;
	private static final int HOMEPAGE = 8;
	private static final int EMAIL = 9;
	private static final int SKYPE = 10;
	private static final int IMG_URL = 11;
	private static final int GROUP = 12;
	
	/* array containing all the textfields */
	private JTextField[] textFields = new JTextField[13];
	
	/**
	 * Create a new Contact Frame
	 * @param mainFrame
	 * @throws HeadlessException
	 */
	public ContactFrame(MainFrame mainFrame) throws HeadlessException {
		super();
		init();
		this.mainFrame = mainFrame;
		addButton = new JButton("Add");
		setTitle("Add Contact");
		rightPanel.add(new JLabel());
		rightPanel.add(addButton);
		addButton.addActionListener(this);
	}
	/**
	 * Create and Edit Contact Frame
	 * @param mainFrame
	 * @param c contact
	 * @throws HeadlessException
	 */
	public ContactFrame(MainFrame mainFrame, Contact c) throws HeadlessException {
		super();
		init();
		setTitle("Edit "+c.getFullName());
		textFields[FIRST_NAME].setText(c.getFirstname());
		
		textFields[LAST_NAME].setText(c.getLastname());

		textFields[HOME_PHONE].setText(c.getHomeNumber());
		
		textFields[HOME_ADDRESS].setText(c.getHomeAddress());
		
		textFields[WORK_PHONE].setText(c.getOfficeNumber());
		
		textFields[WORK_ADDRESS].setText(c.getCompanyAddress());
		
		textFields[MOBILE].setText(c.getPersonnalMobile());
		
		textFields[WORK_MOBILE].setText(c.getWorkMobile());
		
		textFields[HOMEPAGE].setText(c.getHomepage());
		
		textFields[EMAIL].setText(c.getPersonnalEmail());
		
		textFields[SKYPE].setText(c.getSkypeUsername());
		
		setFileName(c.getImgUrl().substring(c.getImgUrl().lastIndexOf("/")+1));
		
		textFields[GROUP].setText(c.getGroup());
		contact = c;
		this.mainFrame = mainFrame;
		saveButton = new JButton("Save");
		rightPanel.add(new JLabel());
		rightPanel.add(saveButton);
		saveButton.addActionListener(this);
	}
	
	/**
	 * Initializes the display
	 */
	public void init(){
		
		
		setMinimumSize(new Dimension(500,250));
		//setPreferredSize(new Dimension(500,250));
		setLocationRelativeTo(null);
		setDefaultCloseOperation(HIDE_ON_CLOSE);
		
		mainPanel = new JPanel();
		
		boxPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		mainPanel.add(boxPanel);
		leftPanel = new JPanel(new GridLayout(7,2));
		rightPanel = new JPanel(new GridLayout(7,2));
		boxPanel.add(leftPanel);
		boxPanel.add(rightPanel);
		
		textFields[FIRST_NAME] = new JTextField();
		leftPanel.add(new JLabel("FirstName"));
		leftPanel.add(textFields[0]);
		
		textFields[LAST_NAME] = new JTextField();
		leftPanel.add(new JLabel("Last Name"));
		leftPanel.add(textFields[1]);
		
		textFields[HOME_PHONE] = new JTextField();
		leftPanel.add(new JLabel("Home Phone"));
		leftPanel.add(textFields[2]);
		
		textFields[HOME_ADDRESS] = new JTextField();
		leftPanel.add(new JLabel("Home Address"));
		leftPanel.add(textFields[3]);
		
		textFields[4] = new JTextField();
		leftPanel.add(new JLabel("Work Phone"));
		leftPanel.add(textFields[4]);
		
		textFields[WORK_ADDRESS] = new JTextField();
		leftPanel.add(new JLabel("Work Address"));
		leftPanel.add(textFields[5]);
		
		textFields[GROUP] = new JTextField();
		leftPanel.add(new JLabel("Contact group"));
		leftPanel.add(textFields[GROUP]);
		
		textFields[MOBILE] = new JTextField();
		rightPanel.add(new JLabel("Mobile Phone"));
		rightPanel.add(textFields[6]);
		
		textFields[WORK_MOBILE] = new JTextField();
		rightPanel.add(new JLabel("Work Mobile Phone"));
		rightPanel.add(textFields[7]);
		
		textFields[HOMEPAGE] = new JTextField();
		rightPanel.add(new JLabel("Homepage"));
		rightPanel.add(textFields[8]);
		
		textFields[EMAIL] = new JTextField();
		rightPanel.add(new JLabel("Personnal Email"));
		rightPanel.add(textFields[9]);
		
		textFields[SKYPE] = new JTextField();
		rightPanel.add(new JLabel("Skype Username"));
		rightPanel.add(textFields[10]);
		
		FileNameExtensionFilter filter = new FileNameExtensionFilter("image file", new String[] {"jpg", "jpeg", "gif", "png"});
		choseButton = new JButton("Select a Picture");
		choseButton.addActionListener(this);
		rightPanel.add(choseButton);
		imgChooser = new JFileChooser();
		imgChooser.setFileFilter(filter);
		imgName = new JLabel("No image selected");
		rightPanel.add(imgName);
		this.add(mainPanel);

		
	}
	@Override
	public void actionPerformed(ActionEvent e) {

        if (e.getSource() == choseButton) {
            int returnVal = imgChooser.showOpenDialog(ContactFrame.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = imgChooser.getSelectedFile();
         
                setFileName(file.getName());
                
                
            }


        }
        //if save or edit is pressed, send data back to the main frame
        if ((e.getSource() == addButton)||(e.getSource() == saveButton)) {
            retrieveData();//retrieve and send data to controller
            dispose();//exit the window
        }
		
	}
	
	private void setFileName(String filename){
		if(filename.length()>18)
        {
            imgName.setText("..."+filename.substring(filename.length()-18, filename.length()-1));

        }else{
        	imgName.setText(filename);
        }
	}
	/**
	 * Sends contact data to controller
	 */
	private void retrieveData(){
		
		/* array to contain all contact info */
		String[] data = new String[13];
		
		
		/* get all the textfields data and save it in the array */
		for (int i = 0; i < textFields.length; i++) {
			if(i!=11)
			{
				if(!textFields[i].equals(""))
				data[i] = textFields[i].getText();
				System.out.println(textFields[i].getText());
			}
				
		}
		/* get the image url if set */
		if(imgChooser.getSelectedFile()!=null){
			data[11]=imgChooser.getSelectedFile().getAbsolutePath();
		}else {
			data[11]="";
		}
		
		if (contact!=null)
		{
			/* Update the edited contact */
			contact.update(data[FIRST_NAME], data[LAST_NAME], data[WORK_ADDRESS], data[HOME_ADDRESS], data[HOME_PHONE], data[WORK_PHONE], data[MOBILE], data[WORK_MOBILE], data[HOMEPAGE], data[EMAIL], data[IMG_URL], data[SKYPE], data[GROUP]);
			this.mainFrame.retrieveContact();
		}else
		{
			/* Create a contact and send it to the main frame*/
			Contact new_contact = new Contact(data[FIRST_NAME], data[LAST_NAME], data[WORK_ADDRESS], data[HOME_ADDRESS], data[HOME_PHONE], data[WORK_PHONE], data[MOBILE], data[WORK_MOBILE], data[HOMEPAGE], data[EMAIL], data[IMG_URL], data[SKYPE],data[GROUP]);
			this.mainFrame.retrieveContact(new_contact);
		}
		
	}
}
